<?php

namespace Console\Logic;

use \Common\Logic\BaseLogic;

/**
 * 族谱控制器
 */
class PRLogic extends BaseLogic {

    private $pigeonModel;
    private $sysinfoModel;

    /**
     * 用数组形式保存族谱拼接的所有配置
     * @var type 
     */
    private $drawConf = array();

    public function __construct() {
        parent::__construct();
        $this->pigeonModel = D('Pigeon');
        $this->sysinfoModel = D('Sysinfo');
    }

    public function init($pigeonId, $type = 0) {
        //取出所有的族谱中的信鸽列表
        $pigeonList = $this->getPigeonPRList($pigeonId);
        if (empty($pigeonList)) {
            return static::$res->err("未找到信鸽数据");
        }

        /**
         * 丰满模式
         */
        if ($type == 1) {
            $dic = array(
                "self", "f", "f_f", "f_f_f", "f_f_m", "f_m", "f_m_f", "f_m_m",
                "m", "m_f", "m_f_f", "m_f_m", "m_m", "m_m_f", "m_m_m"
            );

            foreach ($dic as $key) {
                if (empty($pigeonList[$key])) {
                    $pigeonList[$key] = 1;
                }
            }
        }

        $sysInfo = $this->sysinfoModel->find();
        if (empty($sysInfo["logo"])) {
            return static::$res->err("请后台设置logo");
        }

        $this->initDrawConf($pigeonList, $sysInfo);

        return static::$res->suc("成功");
    }

    /**
     * 根据配置，画出pr图
     * @return type
     */
    public function draw() {
        $drawConf = $this->drawConf;
        $create = $drawConf["create"];
        unset($drawConf["create"]);
        ob_clean();
        $img = imagecreatetruecolor($create['w'], $create['h']);
        $white = imagecolorallocate($img, 255, 255, 255);
        $black = imagecolorallocate($img, 0, 0, 0);

        imagefill($img, 0, 0, $white);

        foreach ($drawConf as $vo) {
            if ($vo["type"] == 1) {
                $tempImg = imagecreatefromstring(file_get_contents($vo["url"]));
                if ($tempImg) {
                    imagecopyresampled($img, $tempImg, $vo['x'], $vo['y'], 0, 0,
                            imagesx($tempImg), imagesy($tempImg), imagesx($tempImg), imagesy($tempImg));
                    imagedestroy($tempImg);
                }
            }

            if ($vo["type"] == 2) {
                $fontUrl = WEB_PATH . "/ImgTemp/msyh.ttf";
                $fontSize = $vo["fontSize"] ? $vo["fontSize"] : 14;
                imagefttext($img, $fontSize, 0, $vo['x'], $vo['y'], $black, $fontUrl, $vo["text"]);
            }
        }

        $prUrl = "/pigeonSys/ImgFile/" . date("Ymd") . "/" . time() . "_" . rand(1111, 9999) . '.jpg';
        $prUrlName = WEB_PATH . "/.." . $prUrl;

//生成png 图像
//header('Content-Type: image/png');
//imagepng($img);
//exit;

        $path = dirname($prUrlName);
        is_dir($path) or mkdir($path, 0777, true);

        if (!imagejpeg($img, $prUrlName)) {
            return static::$res->err("图片保存失败");
        }
        imagedestroy($img);

        return static::$res->suc("成功", $prUrl);
    }

    /**
     * 初始化画图配置
     * @param type $pigeonList
     * @param type $sysInfo
     */
    public function initDrawConf($pigeonList, $sysInfo) {
        $cooLogic = A('Console/CooDic', 'Logic');
        $drawConf = array();

        $drawConf["create"] = $cooLogic->body;
//        $drawConf["headerLine"] = $cooLogic->headerLine;

        $logoCoo = $cooLogic->logo;
        $logoCoo["url"] = WEB_PATH . "/../" . $sysInfo["logo_mini"];
        $drawConf["logo"] = $logoCoo;

        $drawConf["footerLine"] = $cooLogic->footerLine;

        $footerText = $cooLogic->footerText;
        $footerText["text"] = $this->getFooterText($sysInfo);
        $drawConf["footerText"] = $footerText;

        $prDrawConf = $this->getPrDrawConf($pigeonList, $cooLogic);
        $drawConf = array_merge($drawConf, $prDrawConf);

        $this->drawConf = $drawConf;
    }

    public function getPrDrawConf($pigeonList, $cooLogic) {
        $selfCoo = $cooLogic->self;
        $parentCoo = $cooLogic->parent;
        $grandCoo = $cooLogic->grand;
        $gParents = $cooLogic->gParents;

        $padding = 10;

        $conf = array();
        foreach ($pigeonList as $key => $vo) {
            if ($key == "self") {
                $coo = $selfCoo;
                $conf["self_bk"] = array(
                    "type" => 1,
                    "x" => $coo["x"],
                    "y" => $coo["y"],
                    "url" => $coo["url"],
                );

                if (!is_array($vo)) {
                    continue;
                }

                //身形和眼睛图片
                if ($vo["body_eye_mini_img"] && $vo["pr_type"] != 1) {
                    $conf["self_be"] = array(
                        "type" => 1,
                        "x" => $conf["self_bk"]["x"] + 20,
                        "y" => $conf["self_bk"]["y"] + 20,
                        "url" => WEB_PATH . "/.." . $vo["body_eye_mini_img"],
                    );
                }

                $textHeight = $coo["h"] - 320;
                $textY = $conf["self_bk"]["y"] + 270;
                if (empty($conf["self_be"])) {
                    $textHeight = $coo["h"] - 60;
                    $textY = $conf["self_bk"]["y"] + 40;
                }

                $fontSize = 18;
                $selfText = $this->getPigeonText($vo, $fontSize, $textHeight);

                $conf["self_text"] = array(
                    "type" => 2,
                    "x" => $conf["self_bk"]["x"] + 20,
                    "y" => $textY,
                    "text" => $selfText,
                    "fontSize" => $fontSize
                );
            } else if ($key == "f" || $key == "m") {
                $coo = $parentCoo;

                if ($key == "f") {
                    $y = ($selfCoo["y"] + $selfCoo["h"] / 2) - $padding - $coo["h"];
                } else {
                    $y = $selfCoo["y"] + $selfCoo["h"] / 2 + $padding;
                }

                $conf[$key . "_bk"] = array(
                    "type" => 1,
                    "x" => $coo["x"],
                    "url" => $coo["url"],
                    "y" => $y
                );

                if (!is_array($vo)) {
                    continue;
                }

                //身形和眼睛图片
                if ($vo["body_eye_mini_img"] && $vo["pr_type"] != 1) {
                    $conf[$key . "_be"] = array(
                        "type" => 1,
                        "x" => $conf[$key . "_bk"]["x"] + 50,
                        "y" => $conf[$key . "_bk"]["y"] + 20,
                        "url" => WEB_PATH . "/.." . $vo["body_eye_mini_img"],
                    );
                }

                $textHeight = $coo["h"] - 320;
                $textY = $conf[$key . "_bk"]["y"] + 270;
                if (empty($conf[$key . "_be"])) {
                    $textHeight = $coo["h"] - 60;
                    $textY = $conf[$key . "_bk"]["y"] + 40;
                }

                $fontSize = 16;
                $selfText = $this->getPigeonText($vo, $fontSize, $textHeight);

                //输出介绍文字
                $conf[$key . "_text"] = array(
                    "type" => 2,
                    "x" => $conf[$key . "_bk"]["x"] + 50,
                    "y" => $textY,
                    "text" => $selfText,
                    "fontSize" => $fontSize
                );
            } else {
                $keys = explode("_", $key);
                $count = count($keys);
                if ($count == 2) {
                    $coo = $grandCoo;
                    $parent = $conf[$keys[0] . "_bk"];
                    if ($keys[1] == "f") {
                        $y = ($parent['y'] + $parentCoo["h"] / 2) - $padding - $coo["h"];
                    } else {
                        $y = ($parent["y"] + $parentCoo["h"] / 2) + $padding;
                    }
                } else {
                    $coo = $gParents;
                    $grand = $conf[$keys[0] . "_" . $keys[1] . "_bk"];
                    if ($keys[2] == "f") {
                        $y = ($grand["y"] + $grandCoo["h"] / 2) - $padding - $coo["h"];
                    } else {
                        $y = ($grand["y"] + $grandCoo["h"] / 2) + $padding;
                    }
                }

                $conf[$key . "_bk"] = array(
                    "type" => 1,
                    "x" => $coo["x"],
                    "y" => $y,
                    "url" => $coo["url"],
                );

                if (!is_array($vo)) {
                    continue;
                }

                $fontSize = 12;
                $selfText = $this->getPigeonText($vo, $fontSize, $coo["h"] - 60);

                //输出介绍文字
                $conf[$key . "_text"] = array(
                    "type" => 2,
                    "x" => $conf[$key . "_bk"]["x"] + 50,
                    "y" => $conf[$key . "_bk"]["y"] + 40,
                    "text" => $selfText,
                    "fontSize" => $fontSize
                );
            }
        }

        return $conf;
    }

    /**
     * 鸽子的介绍文案
     * @param type $info
     * @param type $footSize
     * @param type $height
     */
    public function getPigeonText($info, $footSize, $height) {
        $width = 325 - 40;
        $fontUrl = WEB_PATH . "/ImgTemp/msyh.ttf";

        $content = $info["name"] . PHP_EOL;

        $pigeonLogic = A('Console/Pigeon', 'Logic');
        $sexDic = $pigeonLogic->getSexDic();

        $sexStr = "";
        if ($info["sex"] != 3) {
            $sexStr = $sexDic[$info["sex"]];
        }

        $content .= $info["cid"] . "  " . $info["color"] . "  " . $sexStr . PHP_EOL;

        $bloodContStr = $info["bloodlines_cont"];

        $bloodArr = array();
        preg_match_all("/./u", $bloodContStr, $bloodArr);
        $letter = $bloodArr[0];
        foreach ($letter as $l) {
            if ($l == Chr(13)) {
                $l = PHP_EOL;
            }
            $teststr = $content . $l;
            $testbox = imagettfbbox($footSize, 0, $fontUrl, $teststr);
            $currH = $testbox[1];
            $currW = $testbox[2];

            if ($currH > $height) {
                $content = mb_substr($content, 0, mb_strlen($content, "utf-8") - 4) . "...";
                break;
            }

            if ($currW > $width) {
                $content .= PHP_EOL;
            }
            $content .= $l;
        }

        return $content;
    }

    /**
     * 获取底部的文字
     * @param type $sysInfo
     * @return string
     */
    public function getFooterText($sysInfo) {

        function blank($num = 10) {
            $text = "";
            for ($i = 0; $i < $num; $i++) {
                $text .= " ";
            }
            return $text;
        }

        $text = "";
        $title = $sysInfo["title"];
        $phone = $sysInfo["phone"];
        $wechat = $sysInfo["wechat"];
        $domain = $sysInfo["domain"];

        if (!empty($title)) {
            $text .= $title . blank();
        }

        if (!empty($phone)) {
            $text .= "电话：" . $phone . blank();
        }
        if (!empty($wechat)) {
            $text .= "微信：" . $wechat . blank();
        }

        if (!empty($domain)) {
            $text .= "网址：" . $domain;
        }

        return $text;
    }

    /**
     * 抽取关系列表
     * @param type $pigeonId
     * @param type $resList
     * @param type $key
     * @param int $leval
     * @return type
     */
    public function getPigeonPRList($pigeonId, $resList = array(), $key = "self", $leval = "1") {
        if (empty($pigeonId)) {
            return $resList;
        }

        $where = array(
            "id" => $pigeonId,
            "state" => 1
        );
        $info = $this->pigeonModel->where($where)->find();
        if (empty($info)) {
            return $resList;
        }

        $resList[$key] = $info;

        $leval += 1;
        if ($leval > 4) {
            return $resList;
        }

        $fatherId = $info["father_id"];
        $motherId = $info["mother_id"];

        if (!empty($fatherId)) {
            if ($leval == 2) {
                $fkey = "f";
            } else {
                $fkey = $key . "_f";
            }
            $resList = $this->getPigeonPRList($fatherId, $resList, $fkey, $leval);
        }

        if (!empty($motherId)) {
            if ($leval == 2) {
                $mkey = "m";
            } else {
                $mkey = $key . "_m";
            }
            $resList = $this->getPigeonPRList($motherId, $resList, $mkey, $leval);
        }

        return $resList;
    }

}
